/* eslint-disable no-dupe-class-members */
'use strict';

const BaseService = require('./base');

class ThemeCommentService extends BaseService {
  async add(params) {
    return this.run(async () => {
      const { ctx } = this;
      const result = await ctx.model.ThemeComment.create(params);
      return result;
    });
  }

  async query(theme_id, user_id, param) {
    return this.run(async () => {
      const { ctx, app } = this;
      const Op = app.Sequelize.Op;
      let order = ['id', 'ASC'];
      if (param.time == 'asc') {
        order = ['create_time', 'ASC'];
      }
      if (param.time == 'desc') {
        order = ['create_time', 'DESC'];
      }
      const { rows, count } = await ctx.model.ThemeComment.findAndCountAll({
        include: [
          {
            model: this.ctx.model.User,
            as: 'user'
          },
          {
            model: this.ctx.model.ThemeCommentLike,
            as: 'like'
          },
          {
            model: this.ctx.model.ThemeCommentReply,
            as: 'reply',
            include: [
              {
                model: this.ctx.model.User,
                as: 'user',
                attributes: ['id', 'nickname']
              },
              {
                model: this.ctx.model.User,
                as: 'reply_user',
                attributes: ['id', 'nickname']
              }
            ]
          }
        ],
        where: {
          theme_id,
          delete_time: {
            [Op.is]: null,
          },
        },
        order: [
          order
        ],
        offset: param.page * param.count,
        limit: param.count
      });
      
      rows.forEach(r => {
        r.dataValues.likeCount = r.dataValues.like.length;
        r.dataValues.isLike = this.isLike(r.dataValues.like, user_id);
        delete r.dataValues.like;
      })
      return { item: rows, totalCount: count};
    });
  }

  isLike(like, userId) {
    let isLike = false;
    if (like) {
        like.forEach(l => {
            if (l.dataValues.user_id == userId) {
                
                isLike = true;
            }
        })
    } 
    return isLike;
}

  async delete(id, delete_time) {
    return this.run(async () => {
      const { ctx } = this;
      const deleteValue = await ctx.model.ThemeComment.findOne({
        where: {
          id,
        },
        attributes: [ 'delete_time' ],
      });
      !deleteValue && ctx.helper.commonErr('未查询到数据', {});

      // 判断数据是否已删除
      (deleteValue.dataValues.delete_time) && ctx.helper.commonErr('请勿重复删除', {});
      const result = await ctx.model.ThemeComment.update({ delete_time }, {
        where: {
          id,
        },
      });
      return result;
    });
  }
}

module.exports = ThemeCommentService;
